﻿using System;
using System.Web.UI;
using System.Configuration;
using System.Data;
using System.Web;
using KPIS.GERP.ESS.BLL;

namespace KPIS.GERP.ESS.APP.App_UI.Forms
{
    public partial class Login : Page
    {
        private B_SECURITY_Users userBLL = new B_SECURITY_Users();
        private FIM_SystemControls.FIM_SystemControls sc = new FIM_SystemControls.FIM_SystemControls();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Login page, when load without postback will destroy old session and cookie
                HttpCookie cookie = HttpContext.Current.Request.Cookies["UserDetail"];
                if (cookie != null) cookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Session.Abandon();

                // Single sign-on
                string strUserID = Request.QueryString["id"];
                string strPassword = Request.QueryString["pw"];
                string strLogOut = Request.QueryString["out"];
                string strPageID = Request.QueryString["pid"];
                string strJobsiteID = Request.QueryString["jid"];
                string strEmpTypeID = Request.QueryString["emptype"];
                string strBgmExpGrpID = Request.QueryString["expid"];
                if (strUserID != null) ProcessLogin(strUserID, strPassword);

                // Page login initial
                PanelHeader.BackImageUrl = "~/App_UI/Images/PageViews/" + ConfigurationSettings.AppSettings["Header"];
                SetTextUserFocus();
                txtPassword.Text = String.Empty;
                txtUserID.Text = String.Empty;
                Page.DataBind();
            }
        }

        protected void cmdLogin_Click(object sender, EventArgs e)
        {
            string strUserID = txtUserID.Text.ToUpper().Trim();
            string strPassword = txtPassword.Text.Trim();

            ProcessLogin(strUserID, strPassword);
        }

        protected void ProcessLogin(string strUserID, string strPassword)
        {
            if (strUserID.Length == 0)
            {
                lblError.Text = "กรุณากรอก [รหัสประจำตัว]";
                SetTextUserFocus();
                return;
            }
            else if (strPassword.Length == 0)
            {
                lblError.Text = "กรุณากรอก [รหัสผ่าน]";
                SetTextPasswordFocus();
                return;
            }

            if (!CheckPassword(strUserID, strPassword))
            {
                lblError.Text = "[รหัสผ่าน] ไม่ถูกต้อง";
                SetTextPasswordFocus();
                return;
            }
            else
            {
                Response.Redirect(@"~\App_UI\Forms\SelectSystem.aspx");
            }
        }

        private bool CheckPassword(string strUserID, string strPassword)
        {
            bool bOK = false;
            DataTable dt = userBLL.GetUserInfo(strUserID, strPassword);

            if (dt.Rows.Count > 0)
            {
                // Set session
                DataRow dr = dt.Rows[0];

                Session["EmpSeq"] = dr["emp_seq"].ToString();
                Session["PosSeq"] = dr["pos_seq"].ToString();
                Session["UserSeq"] = dr["user_seq"].ToString();
                Session["WorkingJobSiteSeq"] = dr["working_job_site_seq"].ToString();
                Session["WorkingJobSiteName"] = dr["working_job_site_name"].ToString();
                Session["WorkAreaSeq"] = dr["work_area_seq"].ToString();
                Session["Height"] = hHeight.Value;
                Session["username"] = dr["user_name"].ToString();

                // Set Cookie
                HttpCookie cookie = new HttpCookie("UserDetail");
                cookie["EmpSeq"] = dr["emp_seq"].ToString();
                cookie["PosSeq"] = dr["pos_seq"].ToString();
                cookie["UserName"] = dr["user_name"].ToString();
                cookie["UserSeq"] = dr["user_seq"].ToString();
                cookie["WorkingJobSiteSeq"] = dr["working_job_site_seq"].ToString();
                cookie["Height"] = hHeight.Value;
                cookie["TokenKey"] = Session["TokenKey"] as string;
                cookie["TokenUserTempData"] = Session["TokenUserTempData"] as string;
                cookie.Expires = DateTime.Now.AddDays(1d);
                Response.Cookies.Add(cookie);

                SetSystemControl();
                bOK = true;
            }

            return bOK;
        }

        private void SetSystemControl()
        {
            FIM_SystemControls.M_FIM_SystemControls systemControl = null;
            try
            { 
                systemControl = sc.GetInfo();
                Session["SCInfo"] = systemControl;
            } 
            catch (Exception e)
            {
                if (e.Message == "Unable to connect to the remote server")
                {
                    //Response.Write("ต้องตั้งค่า Connection Web Service GFMS ให้ถูกต้อง");
                    //Session["SCInfo"] = new FIM_SystemControls.M_FIM_SystemControls
                    //{
                    //    created_by = 1,
                    //    created_when = DateTime.Now,
                    //    default_bgm_year = 2558,
                    //    default_currency_seq = 1,
                    //    default_tax_rate = 7,
                    //    default_vat_rate = 7,
                    //    finance_job_site_seq = 1,
                    //    updated_by = 1,
                    //    updated_when = DateTime.Now,
                    //    use_decimal = 2
                    //};
                    //Response.End();
                }
                else
                {
                    Response.Write(e.Message);
                    Response.End();
                }
            }
        }

        public void SetTextUserFocus()
        {
            Page.SetFocus(txtUserID);
        }

        public void SetTextPasswordFocus()
        {
            Page.SetFocus(txtUserID);
        }

        public bool ShowUserListLoginPage
        {
            get { return (ConfigurationSettings.AppSettings["ShowUserListLoginPage"] ?? "").ToLower() == "true"; }
        }
    }
}